package com.angel.intercepter;

import com.angel.shiro.SystemAdminAuthorizingRealm;
import com.angel.socket.WebSocketUsers;
import com.angel.utils.AdminUserUtils;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptorAdapter;

/**
 * 频道拦截器，类似管道，可以获取消息的一下头信息
 *
 * @author Rabit
 */
public class SocketChannelIntercepter extends ChannelInterceptorAdapter {

    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {
        return super.preSend(message, channel);
    }

    @Override
    public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
        // 消息投返回器
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(message);
        if (headerAccessor.getCommand() == null) {
            // 避免非stomp类型，例如心跳检查
            return;
        }
        SystemAdminAuthorizingRealm.Principal principal = AdminUserUtils.getPrincipal();
        String sessionId = headerAccessor.getSessionAttributes().get("sessionId").toString();

        switch (headerAccessor.getCommand()) {
            case CONNECT:
                connect(sessionId);
                break;
            case DISCONNECT:
                disconnect(sessionId);
                break;
            case SUBSCRIBE:

                break;
            case UNSUBSCRIBE:

                break;
            default:
                break;
        }
    }


    private void connect(String sessionId) {
//
//        WebSocketUsers.eMap.put(sessionId, principal.getEmployee());
        System.out.println("connect sessionId:" + sessionId);
    }

    private void disconnect(String sessionId) {
        System.out.println("disconnect sessionId:" + sessionId);
        //用户下线操作
        WebSocketUsers.eMap.remove(sessionId);
    }

    @Override
    public void afterSendCompletion(Message<?> message, MessageChannel channel, boolean sent, Exception ex) {
        SystemAdminAuthorizingRealm.Principal principal = AdminUserUtils.getPrincipal();
        super.afterSendCompletion(message, channel, sent, ex);
    }
}
